package com.yiqi.news.mvp.ui.activity

import android.Manifest
import android.content.Intent
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v4.view.ViewPager
import android.view.View
import butterknife.OnClick

import com.jess.arms.base.BaseActivity
import com.jess.arms.di.component.AppComponent
import com.jess.arms.utils.ArmsUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import com.yiqi.huize.isNull

import com.yiqi.news.di.component.DaggerImageComponent
import com.yiqi.news.di.module.ImageModule
import com.yiqi.news.mvp.contract.ImageContract
import com.yiqi.news.mvp.presenter.ImagePresenter

import com.yiqi.news.R
import com.yiqi.news.app.service.UserController
import com.yiqi.news.mvp.ui.fragment.BigImageFragment
import kotlinx.android.synthetic.main.activity_image.*
import java.util.ArrayList
import java.util.HashMap
import android.support.v4.app.ActivityCompat.shouldShowRequestPermissionRationale
import android.Manifest.permission.READ_PHONE_STATE
import android.net.Uri
import android.os.AsyncTask
import com.bumptech.glide.Glide
import com.bumptech.glide.request.target.Target
import com.socks.library.KLog
import com.yiqi.news.app.utils.FileUtils
import com.yiqi.news.mvp.ui.adapter.CommentAdapter
import java.io.File
import java.lang.System as System


/**
 * ================================================
 * Description:
 * <p>
 * Created by MVPArmsTemplate on 06/26/2019 16:38
 * <a href="mailto:jess.yan.effort@gmail.com">Contact me</a>
 * <a href="https://github.com/JessYanCoding">Follow me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms">Star me</a>
 * <a href="https://github.com/JessYanCoding/MVPArms/wiki">See me</a>
 * <a href="https://github.com/JessYanCoding/MVPArmsTemplate">模版请保持更新</a>
 * ================================================
 */
/**
 * 如果没presenter
 * 你可以这样写
 *
 * @ActivityScope(請注意命名空間) class NullObjectPresenterByActivity
 * @Inject constructor() : IPresenter {
 * override fun onStart() {
 * }
 *
 * override fun onDestroy() {
 * }
 * }
 */
class ImageActivity : BaseActivity<ImagePresenter>(), ImageContract.View, ViewPager.OnPageChangeListener {

    private val mRxPermissions: RxPermissions by lazy {
        return@lazy RxPermissions(this)
    }

    override fun onPageScrollStateChanged(p0: Int) {

    }

    override fun onPageScrolled(p0: Int, p1: Float, p2: Int) {

    }

    override fun onPageSelected(position: Int) {
        mCurrentPosition = position

        setIndicator(mCurrentPosition)
    }

    private val TAG = ImageActivity::class.java!!.getSimpleName()
    public val IMG_URLS = "mImageUrls"
    public val POSITION = "position"


    private var mImageUrls: List<String> = ArrayList()
    private val mFragments = ArrayList<BigImageFragment>()
    private var mCurrentPosition: Int = 0
    private val mDownloadingFlagMap = HashMap<Int, Boolean>()//用于保存对应位置图片是否在下载的标识

    override fun setupActivityComponent(appComponent: AppComponent) {
        DaggerImageComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .imageModule(ImageModule(this))
                .build()
                .inject(this)
    }


    override fun initView(savedInstanceState: Bundle?): Int {
        return R.layout.activity_image //如果你不需要框架帮你设置 setContentView(id) 需要自行设置,请返回 0
    }


    override fun initData(savedInstanceState: Bundle?) {

    }

    private fun setIndicator(position: Int) {
        tv_indicator.text = ((position + 1).toString() + "/" + mImageUrls.size)//设置当前的指示
    }


    override fun showMessage(message: String) {
        ArmsUtils.snackbarText(message)
    }

    override fun launchActivity(intent: Intent) {
        ArmsUtils.startActivity(intent)
    }

    override fun killMyself() {
        finish()
    }

    internal inner class MyPagerAdapter(fm: FragmentManager) : FragmentPagerAdapter(fm) {

        override fun getItem(position: Int): Fragment {
            return mFragments[position]
        }

        override fun getCount(): Int {
            return mFragments.size
        }
    }

    @OnClick(R.id.tv_save)
    fun onClick(view: View) {
        when (view.id) {
            R.id.tv_save -> {
                mRxPermissions
                        .request(Manifest.permission.CAMERA)
                        .subscribe { granted ->
                            if (granted) { // Always true pre-M
                                //保存图片
                                downloadImg()
                            } else {
                                showMessage(getString(R.string.write_storage_permission_deny))
                            }
                        }
            }

        }
    }

    private fun downloadImg() {
        val imgUrl = mImageUrls[mCurrentPosition]
        val isDownlading = mDownloadingFlagMap[mCurrentPosition]
        if ((!isDownlading!!)!!) {
            //如果不是正在下载，则开始下载
            mDownloadingFlagMap[mCurrentPosition] = true//更改标识为下载中
            DownloadImgTask(mCurrentPosition).execute(imgUrl)
        }
    }

    internal inner class DownloadImgTask(private val mPosition: Int) : AsyncTask<String, Int, Void>() {

        override fun doInBackground(vararg params: String): Void? {
            val imgUrl = params[0]
            var file: File? = null
            try {
                val future = Glide
                        .with(this@ImageActivity)
                        .load(imgUrl)
                        .downloadOnly(Target.SIZE_ORIGINAL, Target.SIZE_ORIGINAL)
                file = future.get()

                val filePath = file!!.absolutePath
                val destFileName = "${System.currentTimeMillis()}${FileUtils.getImageFileExt(filePath)}"
//                val destFileName = System.currentTimeMillis() +
                val destFile = File(FileUtils.getDir(""), destFileName)

                FileUtils.copy(file, destFile)// 保存图片

                // 最后通知图库更新
                sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,
                        Uri.fromFile(File(destFile.path))))
            } catch (e: Exception) {
                KLog.e("DownloadImgTask", e.message)
            }

            return null
        }

        override fun onPostExecute(aVoid: Void) {
            mDownloadingFlagMap[mPosition] = false//下载完成后更改对应的flag
            showMessage("保存成功，图片所在文件夹:SD卡根路径/TouTiao")
        }

        protected override fun onProgressUpdate(vararg values: Int?) {
            KLog.i("onProgressUpdate", "progress: " + values[0])
        }
    }

}
